// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.FBAInvoiceDetail;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.FBAInvoiceDetailMapper;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailCancelListAction;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVo;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVoPages;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailSearchParamPo;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailVo;
import com.fowo.api.service.FBAInvoiceDetailService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发货单详细 服务实现基类
 * @author 蜂窝蜜造平台 配置人：袁江，王阳阳
 */
@Slf4j
@DataObjectType(FBAInvoiceDetail.class)
@DS("ds24")
public class FBAInvoiceDetailBaseServiceImpl
  extends ServiceImpl<FBAInvoiceDetailMapper, FBAInvoiceDetail>
  implements FBAInvoiceDetailService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("nameName", "p.`name`");
      put("shopIdShopName", "si.`shop_name`");
      put("parentFBAInvoiceLogisticsProvider", "fbai.`logistics_provider`");
      put("warehouseName", "w.`name`");
      put("shipmentShopShopName", "si2.`shop_name`");
      put("warehouseBinStorageBin", "wb.`storage_bin`");
      put("outBingIdStorageBin", "wb2.`storage_bin`");
      put("inBingIdStorageBin", "wb3.`storage_bin`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected FBAInvoiceDetailService self;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected FBAInvoiceDetailCancelListAction fBAInvoiceDetailCancelListAction;

  @Resource
  protected Validator validator;

  /**
   * 创建发货单详细
   * @param model 发货单详细
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FBAInvoiceDetailVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInvoiceDetail entity = new FBAInvoiceDetail();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("发货单详细保存失败");
  }

  /**
   * 批量更新 发货单 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByParentFBAInvoice(
    Long parentFBAInvoice,
    List<FBAInvoiceDetailItemVo> list
  ) throws Exception {
    for (FBAInvoiceDetailItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      FBAInvoiceDetail item = new FBAInvoiceDetail();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getParentFBAInvoice() == null) {
        item.setId(null);
        item.setParentFBAInvoice(parentFBAInvoice);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 返回 发货单 下属多级分页
   */
  @Override
  public Map<String, Page<FBAInvoiceDetailItemVoPages>> pagesByParentFBAInvoice(
    FBAInvoiceDetailSearchParamPo search
  ) {
    search.setDisableDataPremissions(true);
    List<FBAInvoiceDetailItemVoPages> listMap =
      baseMapper.selectPagesByParentFBAInvoice(search);
    Map<Long, List<FBAInvoiceDetailItemVoPages>> pageMap = listMap
      .stream()
      .collect(
        Collectors.groupingBy(FBAInvoiceDetailItemVoPages::getParentFBAInvoice)
      );
    Map<String, Page<FBAInvoiceDetailItemVoPages>> result = new HashMap<>();
    for (Map.Entry<Long, List<FBAInvoiceDetailItemVoPages>> listEntry : pageMap.entrySet()) {
      Page<FBAInvoiceDetailItemVoPages> page = new Page<>(
        1,
        search.getPageSize(),
        listEntry.getValue().get(0).getPartRows()
      );
      page.setRecords(listEntry.getValue());
      result.put(listEntry.getKey().toString(), page);
    }
    return result;
  }

  /**
   * 更新发货单详细
   * @param model 发货单详细
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FBAInvoiceDetailVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInvoiceDetail entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货单详细不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "shipmentCode",
      "msku",
      "fnsku",
      "asin",
      "parentAsin",
      "sku",
      "name",
      "shopId",
      "country",
      "planSendQuantity",
      "declarationQuantity",
      "planShipCode",
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新发货单详细（带空值）
   * @param model 发货单详细
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FBAInvoiceDetailVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInvoiceDetail entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货单详细不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        model.getPicUrl() != null,
        FBAInvoiceDetail::getPicUrl,
        JSON.toJSONString(model.getPicUrl())
      )
      .setSql(model.getPicUrl() == null, "pic_url = null")
      .set(FBAInvoiceDetail::getSendQuantity, model.getSendQuantity())
      .set(FBAInvoiceDetail::getTotalSuttle, model.getTotalSuttle())
      .set(FBAInvoiceDetail::getTotalGross, model.getTotalGross())
      .set(FBAInvoiceDetail::getTotalVolume, model.getTotalVolume())
      .set(FBAInvoiceDetail::getParentFBAInvoice, model.getParentFBAInvoice())
      .set(FBAInvoiceDetail::getLastUpdateTime, model.getLastUpdateTime())
      .set(FBAInvoiceDetail::getLastUpdateUser, model.getLastUpdateUser())
      .set(FBAInvoiceDetail::getShipmentShopFnsku, model.getShipmentShopFnsku())
      .set(FBAInvoiceDetail::getShipmentShop, model.getShipmentShop())
      .set(FBAInvoiceDetail::getBoxNum, model.getBoxNum())
      .set(FBAInvoiceDetail::getBoxList, model.getBoxList())
      .set(FBAInvoiceDetail::getBoxGross, model.getBoxGross())
      .set(FBAInvoiceDetail::getBoxLength, model.getBoxLength())
      .set(FBAInvoiceDetail::getBoxWidth, model.getBoxWidth())
      .set(FBAInvoiceDetail::getBoxHeight, model.getBoxHeight())
      .set(FBAInvoiceDetail::getQuantityInCase, model.getQuantityInCase())
      .set(FBAInvoiceDetail::getCbm, model.getCbm())
      .set(FBAInvoiceDetail::getTatolWeight, model.getTatolWeight())
      .set(FBAInvoiceDetail::getTatolVolumeWeight, model.getTatolVolumeWeight())
      .set(FBAInvoiceDetail::getOneSuttle, model.getOneSuttle())
      .set(FBAInvoiceDetail::getOneGross, model.getOneGross())
      .set(FBAInvoiceDetail::getPackageLength, model.getPackageLength())
      .set(FBAInvoiceDetail::getPackageWidth, model.getPackageWidth())
      .set(FBAInvoiceDetail::getPackageHeight, model.getPackageHeight())
      .set(FBAInvoiceDetail::getWhbCode, model.getWhbCode())
      .set(FBAInvoiceDetail::getOutBingId, model.getOutBingId())
      .eq(FBAInvoiceDetail::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FBAInvoiceDetailSearchParamPo search) {
    return false;
  }

  /**
   * 删除发货单详细
   * @param id 发货单详细的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除发货单详细
   * @param ids 发货单详细的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过计划发货量查询发货单详细主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByPlanSendQuantity(Integer planSendQuantity) {
    return this.baseMapper.getIdByPlanSendQuantity(planSendQuantity);
  }

  /**
   * 通过计划发货量查询发货单详细多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByPlanSendQuantity(List<Integer> list) {
    return this.baseMapper.getIdsByPlanSendQuantity(list);
  }

  /**
   * 通过发货单详细主键查询计划发货量
   */
  @Override
  public Integer getPlanSendQuantityById(Long id) {
    return this.baseMapper.getPlanSendQuantityById(id);
  }

  /**
   * 通过发货单详细主键查询计划发货量列表
   */
  @Override
  public List<Integer> getPlanSendQuantityByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getPlanSendQuantityByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (Integer) stringObjectMap.get("planSendQuantity")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 发货单详细的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public FBAInvoiceDetailVo getVoById(Long id) throws Exception {
    FBAInvoiceDetailVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询发货单详细
   * @param search 查询条件
   * @return 发货单详细分页查询结果
   */
  @Override
  public Page<FBAInvoiceDetailItemVo> pageSearch(
    FBAInvoiceDetailSearchParamPo search
  ) {
    Page<FBAInvoiceDetailItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FBAInvoiceDetailItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 发货单详细快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FBAInvoiceDetailOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FBAInvoiceDetailItemVo>> searchOptions(
    FBAInvoiceDetailSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询发货单详细
   * @param search 查询条件
   * @return 发货单详细列表查询结果
   */
  @Override
  public List<FBAInvoiceDetailItemVo> search(
    FBAInvoiceDetailSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询发货单详细最后更新时间
   * @param search 查询条件
   * @return 发货单详细最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FBAInvoiceDetailSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void cancelList(Long id) throws Exception {
    if (fBAInvoiceDetailCancelListAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceDetailCancelListAction.run(id);
  }
}
